import axios from 'axios'
import { Message } from 'element-ui'
import { stringify } from 'qs'
import store from '@/store'
import objectTool from '@/utils/object-tool'

// 创建实例
const Instance = axios.create({
  baseURL: process.env.BASE_URL,
  withCredentials: true,
  timeout: 12e5
})

// http request 拦截器
Instance.interceptors.request.use(
  config => {
    // 根据请求方法构建请求参数和数据
    const needToken = config.url.indexOf('sysMenu/getMenu') > -1 ||
      config.url.indexOf('loginOut') > -1
    const token = store.state.auth.token
    if (token) config.headers.token = token
    if (config.method.toUpperCase() === 'POST') {
      if (config.data) {
        console.log(config.data)
        config.data.createTime = null
        config.data.createUser = null
        config.data.updateTime = null
        config.data.updateUser = null
        objectTool.deleteNoValue(config.data)
      }
     
      config.data = needToken ? stringify({
        ...config.data,
        token
      }, { allowDots: true }) : stringify(config.data, { allowDots: true })
      
    }
    return config
  },
  error => {
    Message({
      message: '错误的传参'
    })
    return Promise.reject(error)
  }
)

// http response 拦截器
Instance.interceptors.response.use(
  response => {
    if (response.config.url.indexOf('/export') > -1) {
      //console.log(response)
      return response
    }
    if (response.data.code !== 0) {
      response.data.msg && Message.warning(response.data.msg)
      return Promise.reject(response)
    }
    return response.data.data
  },
  error => {
    const msg = (error.response && error.response.data && error.response.data.errMsg) || '网络异常，请稍后再试'
    if (error.response && error.response.data && error.response.data.errorCode === 90040006) {
      store.dispatch('fedLogoutAction').then(() => {
        location.reload()
      })
      return false
    }
    Message.error(msg)
    return Promise.reject(error)
  }
)

export default Instance
